import os


def hand_prepare_sql(input_file, output_file):
    if not os.path.exists(input):
        raise ValueError('input file path is not exist')
    if not os.path.exists(os.path.dirname(output_file)):
        os.makedirs(os.path.dirname(output_file))

    with open(input_file, encoding='UTF-8') as file:
        lines = file.readlines()
    sql = lines[0]
    param = lines[1]

    params = param.split(',')
    assert sql.count('?') == len(params)
    var_set = set()
    for item in params:
        var_type = item[item.index('(')+1:len(item)-1]
        var_set.add(var_type)
        if var_type == 'String' or var_type == 'Timestamp':
            sql = sql.replace('?', '\'{}\''.format(item[:item.index('(')].strip()), 1)
        else:
            sql = sql.replace('?', item[:item.index('(')], 1)
    # sql = ';\n'.join(sql.split(';'))
    print(sql)
    print(var_set)

    with open(output_file, mode='w', encoding='UTF-8') as file2:
        file2.write(sql)


if __name__ == '__main__':
    input = '../data/sample/sql.txt'
    output = '../data/sample/sql-handled.txt'
    hand_prepare_sql(input_file=input, output_file=output)

